#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
账单产品服务使用示例
"""

import os
import sys
import json
import logging

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from jlpay.services.bill_service import BillService
from jlpay.model.bill import (
    AccountFileDownloadRequest, TransChargeQueryRequest, SettleBillQueryRequest
)
from jlpay.base.config import OrgConfig
from jlpay.utils.log_config import configure_rotating_file_logging

# =================== 常量定义 =====================
# 日志配置常量
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s() - %(message)s'
MAX_LOG_SIZE = 10 * 1024 * 1024  # 10MB
MAX_BACKUP_COUNT = 10

# =================== 日志配置 =====================
# 配置日志系统，使用滚动文件处理器
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
root_logger = configure_rotating_file_logging(
    level=logging.INFO,
    log_dir=log_dir,
    log_name_prefix="jlpay",
    log_format=LOG_FORMAT,
    max_bytes=MAX_LOG_SIZE,
    backup_count=MAX_BACKUP_COUNT,
    propagate=True,
    module_levels={
        'jlpay.http': logging.INFO,
        'jlpay.service': logging.INFO,
        'examples': logging.INFO
    }
)

# 获取示例程序的logger实例
logger = logging.getLogger("examples.bill")
logger.setLevel(logging.INFO)

# =================== 密钥配置 =====================
# SM2公私钥
sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

# 嘉联支付平台公钥
jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""

# =================== 工具函数 =====================
def create_config():
    """
    创建配置对象
    
    Returns:
        OrgConfig实例
    """
    config = OrgConfig.builder() \
        .app_id("1vzougr30f9vcw") \
        .url("https://openapi-uat.jlpay.com") \
        .org_pri_key(sm2_private_key_pem) \
        .org_pub_key(sm2_public_key_pem) \
        .jlpay_pub_key(jlpay_pub_key_pem) \
        .build()
    return config


def send_request_and_handle_response(service_method, operation_name, *args, **kwargs):
    """
    发送请求并处理响应
    
    Args:
        service_method: 服务方法
        operation_name: 操作名称
        *args: 位置参数
        **kwargs: 关键字参数
        
    Returns:
        响应对象
    """
    try:
        response = service_method(*args, **kwargs)
        
        if response.is_success():
            logger.info(f"{operation_name}成功")
            logger.info(f"响应报文：{response.to_dict()}")
        else:
            logger.error(f"{operation_name}失败: {response.ret_code} - {response.ret_msg}[{response.ret_code}]")
        
        return response
    except Exception as e:
        logger.error(f"{operation_name}失败: {str(e)}")
        raise


def download_account_file_demo():
    """
    对账下载示例
    """
    logger.info("开始执行对账下载示例")
    
    # 创建配置和服务
    config = create_config()
    service = BillService(config)
    
    # 调用对账下载接口
    bill_type = "1"        # 日交易账单
    dt = "20250410"        # 请替换为实际的查询日期
    
    request = AccountFileDownloadRequest()
    request.set_bill_type(bill_type).set_dt(dt)
    
    response = send_request_and_handle_response(
        service.download_account_file,
        "对账下载",
        request
    )
    
    # 如果请求成功，可以下载文件
    if response and response.is_success():
        logger.info(f"对账下载成功！")
        logger.info(f"响应报文：{response.to_dict()}")
    else:
        logger.error("对账下载失败")
        if response:
            logger.error(f"响应报文：{response.to_dict()}")
    
    logger.info("对账下载示例执行完毕")


def query_trans_charge_demo():
    """
    手续费查询示例
    """
    logger.info("开始执行手续费查询示例")
    
    # 创建配置和服务
    config = create_config()
    service = BillService(config)
    
    # 调用手续费查询接口
    order_id = "ORDER123456789"  # 请替换为实际的嘉联订单号
    
    request = TransChargeQueryRequest()
    request.set_order_id(order_id)
    
    send_request_and_handle_response(
        service.query_trans_charge,
        "手续费查询",
        request
    )
    
    logger.info("手续费查询示例执行完毕")


def query_settle_bill_demo():
    """
    商户结算账单查询示例
    """
    logger.info("开始执行商户结算账单查询示例")
    
    # 创建配置和服务
    config = create_config()
    service = BillService(config)
    
    # 调用商户结算账单查询接口
    merch_no = "MERCH123456"   # 请替换为实际的嘉联分配的商户号
    start_busi_date = "2025-04-01"  # 请替换为实际的开始订单交易日期
    end_busi_date = "2025-04-10"    # 请替换为实际的结束订单交易日期
    
    request = SettleBillQueryRequest()
    request.set_merch_no(merch_no).set_start_busi_date(start_busi_date).set_end_busi_date(end_busi_date)
    
    send_request_and_handle_response(
        service.query_settle_bill,
        "商户结算账单查询",
        request
    )
    
    logger.info("商户结算账单查询示例执行完毕")


def bill_demo():
    """
    账单产品服务示例
    """
    logger.info("开始执行账单产品服务示例")
    
    # 对账下载示例
    download_account_file_demo()
    
    # 手续费查询示例
    query_trans_charge_demo()
    
    # 商户结算账单查询示例
    query_settle_bill_demo()
    
    logger.info("账单产品服务示例执行完毕")


if __name__ == "__main__":
    logger.info("==================================================")
    logger.info("===== 账单产品服务示例 开始 =====")
    logger.info("==================================================")
    
    bill_demo()
    
    logger.info("==================================================")
    logger.info("===== 账单产品服务示例执行完毕 =====")
    logger.info("==================================================") 